import 'dart:async';
import 'package:charset_converter/charset_converter.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:chat_gpt_flutter/chat_gpt_flutter.dart';
import 'package:chatgpt/api_key.dart';
import 'package:chatgpt/model/question_answer.dart';
import 'package:chatgpt/theme.dart';
import 'package:chatgpt/view/components/chatgpt_answer_widget.dart';
import 'package:chatgpt/view/components/loading_widget.dart';
import 'package:chatgpt/view/components/text_input_widget.dart';
import 'package:chatgpt/view/components/user_question_widget.dart';
import 'package:flutter/material.dart';

class ChatScreen extends StatefulWidget {
  const ChatScreen({Key? key}) : super(key: key);

  @override
  State<ChatScreen> createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  String? answer;
  final loadingNotifier = ValueNotifier<bool>(false);
  final List<QuestionAnswer> questionAnswers = [];

  late ScrollController scrollController;
  late ChatGpt chatGpt;
  late TextEditingController inputQuestionController;
  StreamSubscription<CompletionResponse>? streamSubscription;

  @override
  void initState() {
    inputQuestionController = TextEditingController();
    scrollController = ScrollController();
    chatGpt = ChatGpt(apiKey: openAIApiKey);
    super.initState();
  }

  @override
  void dispose() {
    inputQuestionController.dispose();
    loadingNotifier.dispose();
    scrollController.dispose();
    streamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: kBg500Color,
      appBar: AppBar(
        elevation: 1,
        shadowColor: Colors.white12,
        centerTitle: true,
        title: Text(
          "DeepSeek",
          style: kWhiteText.copyWith(fontSize: 20, fontWeight: kSemiBold),
        ),
        backgroundColor: kBg300Color,
        actions: [
          IconButton(
            icon: Icon(Icons.delete_rounded), // 你可以换成任何你想要的图标
            onPressed: () {
              // 在这里添加按钮被点击后的操作
              setState(() {
                questionAnswers.clear();
              });
            },
            tooltip: '清空聊天记录',
            color: Colors.pinkAccent,
          ),
        ],
      ),
      body: SafeArea(
        child: Column(
          children: [
            buildChatList(),
            TextInputWidget(
              textController: inputQuestionController,
              onSubmitted: () => _sendMessage(),
            )
          ],
        ),
      ),
    );
  }

  Expanded buildChatList() {
    return Expanded(
      child: ListView.separated(
        controller: scrollController,
        separatorBuilder: (context, index) => const SizedBox(
          height: 12,
        ),
        physics: const BouncingScrollPhysics(),
        padding:
            const EdgeInsets.only(bottom: 20, left: 16, right: 16, top: 16),
        itemCount: questionAnswers.length,
        itemBuilder: (BuildContext context, int index) {
          final question = questionAnswers[index].question;
          final answer = questionAnswers[index].answer;

          return Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              UserQuestionWidget(question: question),
              const SizedBox(height: 16),
              ValueListenableBuilder(
                valueListenable: loadingNotifier,
                builder: (_, bool isLoading, __) {
                  if (answer.isEmpty && isLoading) {
                    _scrollToBottom();
                    return const LoadingWidget();
                  } else {
                    return ChatGptAnswerWidget(
                      answer: answer.toString().trim(),
                    );
                  }
                },
              )
            ],
          );
        },
      ),
    );
  }

  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      scrollController.animateTo(
        scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 250),
        curve: Curves.easeInOut,
      );
    });
  }

  Future<void> fetchDeepSeekStreamResponse(String question) async {
    final url = Uri.parse('https://api.deepseek.com/chat/completions');

    // 你的 DeepSeek API Key
    const apiKey = openAIApiKey;

    // 请求体
    final body = jsonEncode({
      "model": "deepseek-chat",
      "messages": [
        {"role": "system", "content": "你是一个有用的代码助手."},
        {"role": "user", "content": question}
      ],
      "stream": false // 是否为流式响应
    });

    // 发送 POST 请求

    try {
      // 创建 HTTP 请求
      final response = await http
          .post(
            url,
            headers: {
              "Content-Type": "application/json",
              "Authorization": "Bearer $apiKey",
            },
            body: body,
          )
          .timeout(const Duration(seconds: 10));

      // 检查响应状态码
      if (response.statusCode == 200) {
        // 逐行读取响应流
        final responseBody = utf8.decode(response.bodyBytes);

        final responseData = jsonDecode(responseBody);

        // final gbkDecodedString = await CharsetConverter.decode('GBK', bytes);
        // final utf8DecodedString = await CharsetConverter.decode('UTF-8', bytes);

        final messageContent = responseData['choices'][0]['message']['content'];
        final msg = responseData['choices'][0]['message'];
        print("Response: $msg");
        setState(() {
          questionAnswers.last.answer.write(messageContent);
          _scrollToBottom();
        });
      } else {
        print('Error: ${response.statusCode}');
        setState(() {
          questionAnswers.last.answer.write("请求失败: ${response.statusCode}");
        });
      }
    } catch (e) {
      print('Exception: $e');
      setState(() => questionAnswers.last.answer.write("请求失败: $e"));
    }
  }

  void _sendMessage() async {
    final question = inputQuestionController.text;
    print("question: $question");
    if (question.isEmpty) return;
    inputQuestionController.clear();
    loadingNotifier.value = true;

    setState(() => questionAnswers
        .add(QuestionAnswer(question: question, answer: StringBuffer())));

    await fetchDeepSeekStreamResponse(question).then((_) {
      loadingNotifier.value = false;
    }).catchError((error) {
      setState(() => questionAnswers.last.answer.write("请求失败: $error"));
      loadingNotifier.value = false;
    });
    ;
    // final testRequest = CompletionRequest(
    //   prompt: [question],
    //   stream: true,
    //   maxTokens: 500,
    //   temperature: 1,
    //   model: ChatGptModel.textDavinci003 as String,
    // );
    //
    // // 处理请求
    // await _streamResponse(testRequest).then((_) {
    //   // 请求成功完成
    //   loadingNotifier.value = false;
    // }).catchError((error) {
    //   // 请求失败
    //   setState(() => questionAnswers.last.answer.write("请求失败: $error"));
    //   loadingNotifier.value = false;
    // });
  }

  Future _streamResponse(CompletionRequest request) async {
    streamSubscription?.cancel();
    try {
      final stream = await chatGpt.createCompletionStream(request);
      streamSubscription = stream?.listen((event) {
        if (event.streamMessageEnd) {
          streamSubscription?.cancel();
        } else {
          setState(() {
            questionAnswers.last.answer.write(event.choices?.first.text);
            _scrollToBottom();
          });
        }
      });
    } catch (e) {
      debugPrint("Error: $e");
      setState(() => questionAnswers.last.answer.write("error"));
    }
  }
}
